/*
 * @Author: RYPY
 * @Date: 2021-02-20 17:48:22
 * @LastEditors: RYPY
 * @LastEditTime: 2021-02-24 09:43:21
 */
var express = require('express');
const {query}=require("../until/DB");
const {v4:uuid}=require("uuid");
const {Msg,getToken,checkToken,getMD5Pwd}=require("../until/config");
var router = express.Router();

//注册业务
router.post("/register",async(req,res,next)=>{
  let {username,password,repwd}=req.body;
  if(!username||!password){
    next({message:"用户名或密码不合法！"});
  }else if(password!==repwd){
    next({message:"两次密码不一致，请确认密码！"});
  }else{
    let [err,result]=await query(`select * from e_member where username="${username}"`);
    if(result.length>0){
      next({message:"用户名已被注册"});
    }else{
      let uid=uuid();
      let createtime=Date.now();
      password=getMD5Pwd(password);
      let [err1,result1]=await query(`insert into e_member(mid,username,password,createdate) value("${uid}","${username}","${password}","${createtime}")`);
      if(!err1){
        res.send(Msg(200,"ok"));
      }else{
        next({message:"注册失败，请稍后再试！"});
      }
    }
  }
});

//登录业务
router.post("/login",async(req,res,next)=>{
  let {username,password}=req.body;
  if(!username||!password){
    next({message:"登录用户名或密码不合法，请检查！"});
  }else{
    password=getMD5Pwd(password);
    let [err,result]=await query(`select * from e_member where username="${username}" and password="${password}"`);
    if(result.length>0){
      let token=getToken({username,uid:result[0].mid});
      res.send(Msg(200,"ok",token));
    }else{
      next({message:"用户名或密码不正确！"});
    }
  }
});

module.exports = router;
